document.addEventListener('DOMContentLoaded', function() {
  const loginContainer = document.querySelector('.login-container');
  const chatContainer = document.querySelector('.chat-container');
  const loginButton = document.querySelector('.login-button');
  const chatMessages = document.getElementById('chat-messages');
  const userInput = document.getElementById('user-input');
  const sendButton = document.getElementById('send-button');
  const visitButton = document.querySelector('.visit-yinliai');
  
  // 查找对话和探索快捷键设置项
  const dialogShortcutItem = Array.from(document.querySelectorAll('.setting-item')).find(
    item => item.querySelector('.setting-label').textContent.includes('对话快捷键')
  );
  const exploreShortcutItem = Array.from(document.querySelectorAll('.setting-item')).find(
    item => item.querySelector('.setting-label').textContent.includes('探索快捷键')
  );
  
  const dialogShortcutValue = dialogShortcutItem.querySelector('.setting-value');
  const exploreShortcutValue = exploreShortcutItem.querySelector('.setting-value');
  
  const YINLIAI_URL = 'https://ai.yinlimedia.com/Creative/Assistant/Douyin';
  const CHROME_SHORTCUTS_URL = 'chrome://extensions/shortcuts';

  // 检查登录状态并更新界面
  function checkLoginStatus() {
    chrome.storage.local.get(['isLoggedIn', 'userToken', 'userName', 'userAvatar'], function(result) {
      if (result.isLoggedIn && result.userToken && result.userName) {
        // 更新登录按钮显示
        updateLoginButton(result.userName, result.userAvatar || 'images/avatar.png');
      } else {
        // 显示未登录状态
        updateLoginButton(null, 'images/avatar.png');
      }
    });
  }

  // 更新登录按钮显示
  function updateLoginButton(nickname, avatar) {
    const loginButton = document.querySelector('.login-button');
    const avatarImg = loginButton.querySelector('.avatar-icon');
    const spanText = loginButton.querySelector('span');

    if (nickname) {
      // 已登录状态
      avatarImg.src = avatar;
      avatarImg.classList.add('logged-in');
      spanText.textContent = nickname;
      loginButton.classList.add('logged-in');
    } else {
      // 未登录状态
      avatarImg.src = 'images/avatar.png';
      avatarImg.classList.remove('logged-in');
      spanText.textContent = '点击登录';
      loginButton.classList.remove('logged-in');
    }
  }

  // 在页面加载时检查登录状态
  checkLoginStatus();

  // 添加相关样式到 styles.css
  const style = document.createElement('style');
  style.textContent = `
    .login-button.logged-in {
      background: #f5f7fa;
    }
    
    .avatar-icon.logged-in {
      border: 2px solid #2563EB;
    }
    
    .login-button.logged-in:hover {
      background: #edf2f7;
    }
  `;
  document.head.appendChild(style);

  // 检查快捷键设置
  function checkShortcutSettings() {
    chrome.commands.getAll(commands => {
      // 检查对话快捷键
      const dialogCommand = commands.find(cmd => cmd.name === 'open-dialog');
      const dialogShortcut = dialogCommand?.shortcut || null;
      
      // 检查探索快捷键
      const exploreCommand = commands.find(cmd => cmd.name === 'explore');
      const exploreShortcut = exploreCommand?.shortcut || null;

      // 保存到storage
      chrome.storage.local.set({ 
        'dialogShortcut': dialogShortcut,
        'exploreShortcut': exploreShortcut
      });

      // 更新显示
      if (dialogShortcutValue) {
        dialogShortcutValue.textContent = dialogShortcut || '未设置';
      }
      if (exploreShortcutValue) {
        exploreShortcutValue.textContent = exploreShortcut || '未设置';
      }

      // 通知content script更新快捷键显示
      chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        if (tabs[0]) {
          chrome.tabs.sendMessage(tabs[0].id, {
            action: 'updateShortcuts',
            dialogShortcut: dialogShortcut,
            exploreShortcut: exploreShortcut
          });
        }
      });
    });
  }

  // 初始化时检查快捷键
  checkShortcutSettings();

  // 点击快捷键设置项跳转到Chrome快捷键设置页面
  function addShortcutClickHandler(element) {
    element.style.cursor = 'pointer';
    element.addEventListener('click', function() {
      chrome.tabs.create({ url: 'chrome://extensions/shortcuts' });
    });
    element.addEventListener('mouseover', function() {
      this.style.backgroundColor = '#f5f5f5';
    });
    element.addEventListener('mouseout', function() {
      this.style.backgroundColor = '';
    });
  }

  // 为两个快捷键设置项添加点击处理
  addShortcutClickHandler(dialogShortcutItem);
  addShortcutClickHandler(exploreShortcutItem);

  // 登录按钮点击事件
  loginButton.addEventListener('click', function() {
    chrome.storage.local.get(['isLoggedIn', 'userToken'], function(result) {
      if (result.isLoggedIn && result.userToken) {
        // 如果已登录，显示用户菜单（可以添加登出等选项）
        showUserMenu();
      } else {
        // 如果未登录，显示登录对话框
        createLoginDialog();
      }
    });
  });

  // 访问按钮点击事件
  visitButton.addEventListener('click', function() {
    chrome.tabs.create({ url: YINLIAI_URL });
  });

  // 移除悬浮按钮相关的设置和事件监听
  chrome.storage.local.get(['floatButtonEnabled', 'windowStyle'], function(result) {
    // 设置窗口显示方式
    const windowStyleSelect = document.querySelector('.window-style');
    if (windowStyleSelect) {
      windowStyleSelect.value = result.windowStyle || 'float';
      windowStyleSelect.addEventListener('change', function() {
        chrome.storage.local.set({ 'windowStyle': this.value });
      });
    }

    // 设置悬浮按钮开关
    const floatButton = document.getElementById('floatButton');
    if (floatButton) {
      // 获取当前状态
      chrome.storage.local.get(['floatButtonEnabled'], function(result) {
        const isEnabled = result.floatButtonEnabled !== undefined ? result.floatButtonEnabled : true;
        floatButton.checked = isEnabled;
        
        // 监听开关变化
        floatButton.addEventListener('change', function() {
          const isEnabled = this.checked;
          console.log('Float button toggle:', isEnabled);
          
          // 保存新状态
          chrome.storage.local.set({ 'floatButtonEnabled': isEnabled }, function() {
            // 通知当前标签页更新悬浮按钮状态
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
              if (tabs[0]) {
                chrome.tabs.sendMessage(tabs[0].id, {
                  action: 'updateFloatButton',
                  isEnabled: isEnabled
                }, (response) => {
                  if (chrome.runtime.lastError) {
                    console.error('Error sending message:', chrome.runtime.lastError);
                    // 不要自动刷新页面
                    console.log('Content script not ready, please refresh the page');
                  } else {
                    console.log('Float button update response:', response);
                  }
                });
              }
            });
          });
        });
      });
    }
  });

  // 初始化开关状态
  chrome.storage.local.get(['showButtons', 'keepUnderline'], function(result) {
    const showButtonsToggle = document.getElementById('showButtons');
    const keepUnderlineToggle = document.getElementById('keepUnderline');

    if (showButtonsToggle) {
      showButtonsToggle.checked = result.showButtons || false;
      showButtonsToggle.addEventListener('change', function() {
        const isEnabled = this.checked;
        console.log('Show buttons toggle:', isEnabled);
        chrome.storage.local.set({ 'showButtons': isEnabled });
      });
    }

    if (keepUnderlineToggle) {
      keepUnderlineToggle.checked = result.keepUnderline || false;
      keepUnderlineToggle.addEventListener('change', function() {
        const isEnabled = this.checked;
        console.log('Keep underline toggle:', isEnabled);
        chrome.storage.local.set({ 'keepUnderline': isEnabled });
      });
    }
  });

  function showLogin() {
    loginContainer.style.display = 'flex';
    chatContainer.style.display = 'none';
  }

  function showChat() {
    loginContainer.style.display = 'none';
    chatContainer.style.display = 'flex';
  }

  // 模拟AI响应的函数
  async function getAIResponse(userMessage) {
    // 这里您需要替换为实际的AI API调用
    // 示例使用一个简单的回复
    return "这是AI的回复消息。在实际应用中，您需要调用真实的AI API。";
  }

  // 添加消息到聊天界面
  function addMessage(message, isUser) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`;
    messageDiv.textContent = message;
    chatMessages.appendChild(messageDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
  }

  // 处理发送消息
  async function handleSend() {
    const message = userInput.value.trim();
    if (!message) return;

    // 添加用户消息
    addMessage(message, true);
    userInput.value = '';

    // 获取并添加AI响应
    const aiResponse = await getAIResponse(message);
    addMessage(aiResponse, false);
  }

  // 事件监听器
  sendButton.addEventListener('click', handleSend);
  userInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  });

  function createLoginDialog() {
    const loginDialog = document.createElement('div');
    loginDialog.className = 'login-dialog-overlay';
    
    loginDialog.innerHTML = `
      <div class="login-dialog">
        <div class="login-dialog-header">
          <h3>登录 YinliAI</h3>
          <div class="login-dialog-close">×</div>
        </div>
        <div class="login-dialog-content">
          <div class="input-group">
            <label for="username">账号</label>
            <input type="text" id="username" placeholder="请输入账号">
          </div>
          <div class="input-group">
            <label for="password">密码</label>
            <input type="password" id="password" placeholder="请输入密码">
          </div>
          <div class="login-error" style="display: none;"></div>
          <button class="login-submit-button">登录</button>
        </div>
      </div>
    `;

    document.body.appendChild(loginDialog);

    // 关闭按钮事件
    const closeButton = loginDialog.querySelector('.login-dialog-close');
    closeButton.addEventListener('click', () => {
      loginDialog.remove();
    });

    // 点击遮罩层关闭
    loginDialog.addEventListener('click', (e) => {
      if (e.target === loginDialog) {
        loginDialog.remove();
      }
    });

    // 登录按钮事件
    const submitButton = loginDialog.querySelector('.login-submit-button');
    const errorDiv = loginDialog.querySelector('.login-error');

    submitButton.addEventListener('click', async () => {
      const username = loginDialog.querySelector('#username').value;
      const password = loginDialog.querySelector('#password').value;

      if (!username || !password) {
        showError('请输入账号和密码');
        return;
      }

      submitButton.disabled = true;
      submitButton.textContent = '登录中...';

      try {
        const response = await fetch('https://ai.yinlimedia.com/api/api/login/index', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            "mobile": username,
            "is_auto": 0,
            "password": password
          })
        });

        const data = await response.json();

        if (data.code == 990) {
          // 保存登录信息到 chrome.storage.local
          chrome.storage.local.set({
            isLoggedIn: true,
            userToken: data.data.openid,
            userAvatar: 'https://avatar.moonshot.cn/avatar/comb9havk6gfi4tgucc0',
            userName: data.data.name,
            loginTime: Date.now()
          }, () => {
            // 更新登录按钮显示
            updateLoginButton(data.data.name, 'https://avatar.moonshot.cn/avatar/comb9havk6gfi4tgucc0');
            
            // 通知 content script 更新悬浮按钮
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
              if (tabs[0]) {
                chrome.tabs.sendMessage(tabs[0].id, {
                  action: 'updateLoginStatus',
                  isLoggedIn: true,
                  userAvatar: 'https://avatar.moonshot.cn/avatar/comb9havk6gfi4tgucc0'
                });
              }
            });
            
            loginDialog.remove();
          });
        } else {
          showError(data.message || '登录失败，请重试');
        }
      } catch (error) {
        showError('网络错误，请重试');
      } finally {
        submitButton.disabled = false;
        submitButton.textContent = '登录';
      }
    });

    function showError(message) {
      errorDiv.textContent = message;
      errorDiv.style.display = 'block';
    }
  }

  // 用户菜单
  function showUserMenu() {
    const menu = document.createElement('div');
    menu.className = 'user-menu';
    menu.innerHTML = `
      <div class="menu-item logout">退出登录</div>
    `;

    // 定位菜单
    const loginButton = document.querySelector('.login-button');
    const rect = loginButton.getBoundingClientRect();
    menu.style.top = rect.bottom + 'px';
    menu.style.left = rect.left + 'px';

    document.body.appendChild(menu);

    // 退出登录
    menu.querySelector('.logout').addEventListener('click', function() {
      chrome.storage.local.remove(['isLoggedIn', 'userToken', 'userName', 'userAvatar'], function() {
        updateLoginButton(null, 'images/avatar.png');
        menu.remove();
      });
    });

    // 点击其他地方关闭菜单
    document.addEventListener('click', function closeMenu(e) {
      if (!menu.contains(e.target) && !loginButton.contains(e.target)) {
        menu.remove();
        document.removeEventListener('click', closeMenu);
      }
    });
  }

  // 添加用户菜单样式
  style.textContent += `
    .user-menu {
      position: absolute;
      background: white;
      border: 1px solid #E5E7EB;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      padding: 4px 0;
      z-index: 1000;
    }

    .menu-item {
      padding: 8px 16px;
      cursor: pointer;
      color: #333;
      font-size: 14px;
    }

    .menu-item:hover {
      background: #F3F4F6;
    }

    .menu-item.logout {
      color: #DC2626;
    }

    .menu-item.logout:hover {
      background: #FEE2E2;
    }
  `;

  // 添加对话按钮点击事件
  const dialogButton = document.querySelector('.setting-item:has(.setting-label:contains("YinliAI 悬浮按钮"))');
  if (dialogButton) {
    dialogButton.addEventListener('click', function() {
      // 获取当前标签页
      chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        if (tabs[0]) {
          // 发送消息给 content script 打开对话框
          chrome.tabs.sendMessage(tabs[0].id, { action: 'openDialog' }, (response) => {
            if (chrome.runtime.lastError) {
              console.error('Error sending message:', chrome.runtime.lastError);
              // 如果 content script 未加载，重新加载页面
              chrome.tabs.reload(tabs[0].id);
            } else {
              console.log('Dialog open response:', response);
              // 关闭 popup
              window.close();
            }
          });
        }
      });
    });
  }
}); 